﻿import 'package:azring/services/device_sn_manager.dart';
import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:image_picker/image_picker.dart';
import '../../../../core/repository/default_api.dart';
import '../../status_logic.dart';

/// 文字记录控制器
class TextRecordLogic extends GetxController {
  /// 食物名称控制器
  final TextEditingController foodNameController = TextEditingController();

  /// 数量控制器
  final TextEditingController quantityController = TextEditingController();

  /// 单位控制器
  final TextEditingController unitController = TextEditingController();

  /// 选中的图片路径
  final RxString selectedImagePath = ''.obs;

  /// 是否可以保存
  final RxBool canSave = false.obs;

  /// 图片选择器
  final ImagePicker _picker = ImagePicker();

  /// 用餐时段（从上一页传入，已经是映射值如 "1", "2", "3"）
  String mealTime = '1';

  /// 选择的日期（从上一页传入）
  DateTime selectedDate = DateTime.now();

  @override
  void onInit() {
    super.onInit();

    // 从路由参数获取用餐时段和日期
    final args = Get.arguments as Map<String, dynamic>?;
    if (args != null) {
      mealTime = args['mealTime'] ?? '1';
      selectedDate = args['selectedDate'] ?? DateTime.now();
    }

    // 监听输入框变化
    foodNameController.addListener(_checkCanSave);
    quantityController.addListener(_checkCanSave);
    unitController.addListener(_checkCanSave);
  }

  @override
  void onClose() {
    foodNameController.dispose();
    quantityController.dispose();
    unitController.dispose();
    super.onClose();
  }

  /// 检查是否可以保存
  void _checkCanSave() {
    canSave.value = foodNameController.text.trim().isNotEmpty;
  }

  /// 选择图片
  Future<void> pickImage() async {
    try {
      // 显示选择对话框
      final result = await Get.dialog<String>(
        AlertDialog(
          backgroundColor: const Color(0xFF282528),
          title: const Text(
            '选择图片',
            style: TextStyle(color: Colors.white),
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                leading: const Icon(Icons.camera_alt, color: Colors.white),
                title: const Text('拍照', style: TextStyle(color: Colors.white)),
                onTap: () => Get.back(result: 'camera'),
              ),
              ListTile(
                leading: const Icon(Icons.photo_library, color: Colors.white),
                title:
                    const Text('从相册选择', style: TextStyle(color: Colors.white)),
                onTap: () => Get.back(result: 'gallery'),
              ),
            ],
          ),
        ),
      );

      if (result != null) {
        final XFile? image = await _picker.pickImage(
          source: result == 'camera' ? ImageSource.camera : ImageSource.gallery,
          maxWidth: 1024,
          maxHeight: 1024,
          imageQuality: 80,
        );

        if (image != null) {
          selectedImagePath.value = image.path;
        }
      }
    } catch (e) {
      Toast.show(
        '选择图片失败：$e',
      );
    }
  }

  /// 保存食物记录
  Future<void> saveFoodRecord() async {
    if (!canSave.value) return;

    try {
      // 构建描述文本
      final String description = foodNameController.text.trim();
      final deviceSnManager = Get.find<DeviceSnManager>();
      final deviceSn = deviceSnManager.getDeviceSn();
      await DefaultApi().addFoodInfoPost<dynamic>(
        deviceSn: deviceSn,
        mealType: mealTime,
        description: description,
        isShowLoading: true,
      );

      Toast.show('记录成功');

      // 刷新StatusController中的饮食记录列表
      try {
        final statusController = Get.find<StatusLogic>();
        await statusController.refreshFoodRecords();
      } catch (e) {
        print('⚠️ 刷新饮食记录列表失败: $e');
      }

      // 延迟返回上一页
      await Future.delayed(const Duration(milliseconds: 500));
      Get.back(result: true);
    } catch (e) {
      Toast.show(
        '保存失败：$e',
      );
    }
  }
}
